package com.weather.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class BaiduWeatherUtil {
    private static final String AK = "0uySY8DWGzuPl34PTOirEUeeV05n9d6P";

    public static String  getWeather(int cityId){
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuffer json = new StringBuffer();
        try {
            URL url = new URL("http://api.map.baidu.com/weather/v1/?district_id="+cityId+"&data_type=now&output=json&ak="+AK);
            //打开和url之间的连接
            URLConnection connection = url.openConnection();

            //建立实际连接
            connection.connect();
            //获取内容
            inputStream= connection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            String temp = null;
            while ((temp = bufferedReader.readLine())!= null){
                json.append(temp);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json.toString();
    }
}
